<template>
  <div class="home">
    <!-- 英雄区域 -->
    <section class="hero-section py-5 my-5" data-aos="fade-up">
      <div class="container">
        <div class="row align-items-center">
          <div class="col-lg-6" data-aos="fade-right" data-aos-delay="200">
            <div class="typing-container mb-3">
              <h1 class="display-4 fw-bold text-primary mb-4 typing-text">
                {{ typedText }}<span class="cursor">|</span>
              </h1>
            </div>
            <p class="lead mb-4 text-animation" data-aos="fade-up" data-aos-delay="400">
              {{ heroData.subtitle || '加载中...' }}
            </p>
            <div class="d-flex flex-wrap gap-3" data-aos="fade-up" data-aos-delay="600">
              <router-link 
                v-for="button in heroData.buttons" 
                :key="button.text"
                :to="button.link" 
                :class="`btn btn-${button.type} btn-lg btn-hover-effect`"
              >
                <i :class="`${button.icon} me-2`"></i>
                {{ button.text }}
                <div class="btn-ripple"></div>
              </router-link>
            </div>
          </div>
          <div class="col-lg-6 text-center" data-aos="fade-left" data-aos-delay="300">
            <div class="avatar-container">
              <img 
                :src="require('@/assets/head.jpg')" 
                alt="头像" 
                class="img-fluid rounded-circle shadow-lg floating-avatar"
                style="max-width: 300px; width: 100%;"
              >
              <div class="avatar-ring"></div>
              <div class="avatar-ring-2"></div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 特色内容 -->
    <section class="features-section py-5">
      <div class="container">
        <h2 class="text-center mb-5">{{ featuresData.title || '博客特色' }}</h2>
        <div class="row g-4">
          <div class="col-md-4" v-for="feature in featuresData.items" :key="feature.id">
            <div class="card h-100 border-0 shadow-sm">
              <div class="card-body text-center p-4">
                <div class="mb-3">
                  <i :class="`bi ${feature.icon} ${feature.color}`" style="font-size: 3rem;"></i>
                </div>
                <h5 class="card-title">{{ feature.title }}</h5>
                <p class="card-text">
                  {{ feature.description }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 最新文章 -->
    <section class="latest-posts py-5 bg-light">
      <div class="container">
        <div class="row">
          <div class="col-12">
            <h2 class="text-center mb-5">{{ latestPostsConfig.title || '最新文章' }}</h2>
          </div>
        </div>
        <div class="row g-4">
          <div class="col-lg-4 col-md-6" v-for="post in latestPosts" :key="post.id">
            <article class="card h-100 border-0 shadow-sm">
              <img 
                :src="post.image" 
                :alt="post.title"
                class="card-img-top"
                style="height: 200px; object-fit: cover;"
              >
              <div class="card-body d-flex flex-column">
                <h5 class="card-title">{{ post.title }}</h5>
                <p class="card-text flex-grow-1">{{ post.excerpt }}</p>
                <div class="mt-auto">
                  <small class="text-muted">
                    <i class="bi bi-calendar me-1"></i>{{ post.date }}
                    <i class="bi bi-eye ms-3 me-1"></i>{{ post.views }}
                  </small>
                  <router-link 
                    :to="`/article/${post.id}`" 
                    class="btn btn-outline-primary btn-sm float-end"
                  >
                    阅读更多
                  </router-link>
                </div>
              </div>
            </article>
          </div>
        </div>
        <div class="text-center mt-5">
          <router-link :to="latestPostsConfig.viewAllLink || '/blog'" class="btn btn-primary btn-lg">
            {{ latestPostsConfig.viewAllText || '查看所有文章' }}
            <i class="bi bi-arrow-right ms-2"></i>
          </router-link>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import { getLatestPosts } from '@/data/blogData'

export default {
  name: 'Home',
  data() {
    return {
      typedText: '',
      fullText: '',
      typeIndex: 0,
      latestPosts: [],
      // API数据
      heroData: {
        title: '',
        subtitle: '',
        buttons: []
      },
      featuresData: {
        title: '',
        items: []
      },
      latestPostsConfig: {
        title: '',
        viewAllText: '',
        viewAllLink: ''
      },
      isLoading: true,
      apiError: null
    }
  },
  mounted() {
    this.loadHomeData()
    this.loadLatestPosts()
    this.initParticles()
  },
  methods: {
    async loadHomeData() {
      try {
        this.isLoading = true
        
        // 调用API获取首页数据
        const response = await fetch('http://localhost:3001/api/home')
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const result = await response.json()
        
        if (result.success && result.data) {
          // 更新各部分数据
          this.heroData = result.data.hero || {}
          this.featuresData = result.data.features || {}
          this.latestPostsConfig = result.data.latestPosts || {}
          
          // 设置打字机效果的文本
          this.fullText = this.heroData.title || '欢迎来到我的博客'
          
          // 开始打字机效果
          this.startTyping()
        } else {
          throw new Error(result.message || 'API返回数据格式错误')
        }
        
      } catch (error) {
        console.error('加载首页数据失败:', error)
        this.apiError = error.message
        
        // 设置默认数据作为后备
        this.setDefaultData()
        this.startTyping()
      } finally {
        this.isLoading = false
      }
    },
    
    setDefaultData() {
      // 后备数据，防止API调用失败
      this.heroData = {
        title: '欢迎来到我的博客',
        subtitle: '这里记录着我的技术分享、生活感悟和成长历程。希望能与你分享知识和经验，共同进步。',
        buttons: [
          { text: '阅读文章', link: '/blog', type: 'primary', icon: 'bi-book' },
          { text: '了解我', link: '/about', type: 'outline-primary', icon: 'bi-person' }
        ]
      }
      
      this.featuresData = {
        title: '博客特色',
        items: [
          {
            id: 1,
            icon: 'bi-code-slash',
            color: 'text-primary',
            title: '技术分享',
            description: '分享前端开发、后端技术、以及各种编程经验和技巧'
          },
          {
            id: 2,
            icon: 'bi-lightbulb',
            color: 'text-warning',
            title: '生活感悟',
            description: '记录生活中的点点滴滴，分享个人成长和思考'
          },
          {
            id: 3,
            icon: 'bi-heart',
            color: 'text-danger',
            title: '兴趣爱好',
            description: '分享摄影、旅行、读书等个人兴趣和爱好'
          }
        ]
      }
      
      this.latestPostsConfig = {
        title: '最新文章',
        viewAllText: '查看所有文章',
        viewAllLink: '/blog'
      }
      
      this.fullText = this.heroData.title
    },
    
    startTyping() {
      // 重置打字机状态
      this.typedText = ''
      this.typeIndex = 0
      
      const typeNextChar = () => {
        if (this.typeIndex < this.fullText.length) {
          this.typedText += this.fullText[this.typeIndex]
          this.typeIndex++
          setTimeout(typeNextChar, 100)
        }
      }
      setTimeout(typeNextChar, 500)
    },
    
    loadLatestPosts() {
      this.latestPosts = getLatestPosts(3)
    },
    initParticles() {
      // 简单的粒子背景效果
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      canvas.width = window.innerWidth
      canvas.height = window.innerHeight
      canvas.style.position = 'fixed'
      canvas.style.top = '0'
      canvas.style.left = '0'
      canvas.style.zIndex = '-3'
      canvas.style.pointerEvents = 'none'
      document.body.appendChild(canvas)
      
      const particles = []
      const particleCount = 50
      
      for (let i = 0; i < particleCount; i++) {
        particles.push({
          x: Math.random() * canvas.width,
          y: Math.random() * canvas.height,
          vx: (Math.random() - 0.5) * 0.5,
          vy: (Math.random() - 0.5) * 0.5,
          size: Math.random() * 2 + 1
        })
      }
      
      const animate = () => {
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        ctx.fillStyle = 'rgba(13, 110, 253, 0.1)'
        
        particles.forEach(particle => {
          particle.x += particle.vx
          particle.y += particle.vy
          
          if (particle.x < 0 || particle.x > canvas.width) particle.vx *= -1
          if (particle.y < 0 || particle.y > canvas.height) particle.vy *= -1
          
          ctx.beginPath()
          ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2)
          ctx.fill()
        })
        
        requestAnimationFrame(animate)
      }
      
      animate()
    }
  }
}
</script>

<style scoped>
.hero-section {
  background: linear-gradient(135deg, rgba(13, 110, 253, 0.15) 0%, rgba(255, 255, 255, 0.80) 100%);
  border-radius: 20px;
  margin: 2rem 0;
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.4);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

/* 打字机效果 */
.typing-text {
  font-family: 'Courier New', monospace;
}

.cursor {
  animation: blink 1s infinite;
  color: #0d6efd;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

/* 头像动画 */
.avatar-container {
  position: relative;
  display: inline-block;
}

.floating-avatar {
  animation: float 6s ease-in-out infinite;
  position: relative;
  z-index: 2;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.avatar-ring {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 320px;
  height: 320px;
  border: 2px solid rgba(13, 110, 253, 0.3);
  border-radius: 50%;
  animation: rotate 20s linear infinite;
  z-index: 1;
}

.avatar-ring-2 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 350px;
  height: 350px;
  border: 1px solid rgba(13, 110, 253, 0.2);
  border-radius: 50%;
  border-top-color: rgba(13, 110, 253, 0.6);
  animation: rotate 15s linear infinite reverse;
  z-index: 1;
}

@keyframes rotate {
  from { transform: translate(-50%, -50%) rotate(0deg); }
  to { transform: translate(-50%, -50%) rotate(360deg); }
}

/* 按钮特效 */
.btn-hover-effect {
  position: relative;
  overflow: hidden;
  transition: all 0.4s ease;
}

.btn-hover-effect:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 25px rgba(13, 110, 253, 0.3);
}

.btn-ripple {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  transition: width 0.6s, height 0.6s, top 0.6s, left 0.6s;
}

.btn-hover-effect:active .btn-ripple {
  width: 300px;
  height: 300px;
  top: calc(50% - 150px);
  left: calc(50% - 150px);
}

/* 卡片增强动画 */
.card {
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  position: relative;
  overflow: hidden;
}

.card:before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.6), transparent);
  transition: left 0.5s;
}

.card:hover:before {
  left: 100%;
}

.card:hover {
  transform: translateY(-10px) scale(1.02);
  box-shadow: 0 20px 40px rgba(0,0,0,0.15) !important;
}

/* 文本动画 */
.text-animation {
  opacity: 0;
  animation: fadeInUp 1s ease-out 1s forwards;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 特色区域增强 */
.features-section .card {
  background: rgba(255, 255, 255, 0.75);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.4);
}

.features-section .card:hover {
  background: rgba(255, 255, 255, 0.85);
}

/* 最新文章区域 */
.latest-posts {
  background: linear-gradient(135deg, rgba(248, 249, 250, 0.75) 0%, rgba(255, 255, 255, 0.80) 100%);
  backdrop-filter: blur(15px);
  border-radius: 20px;
  margin: 2rem 0;
  border: 1px solid rgba(255, 255, 255, 0.4);
}

.latest-posts .card {
  background: rgba(255, 255, 255, 0.75);
  backdrop-filter: blur(10px);
}

.latest-posts .card:hover {
  background: rgba(255, 255, 255, 0.85);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .avatar-ring {
    width: 280px;
    height: 280px;
  }
  
  .avatar-ring-2 {
    width: 310px;
    height: 310px;
  }
  
  .typing-text {
    font-size: 2rem !important;
  }
}

/* 加载动画 */
@keyframes slideInLeft {
  from {
    transform: translateX(-100px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes slideInRight {
  from {
    transform: translateX(100px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 鼠标跟随光标效果 */
.hero-section:hover {
  background: linear-gradient(135deg, rgba(13, 110, 253, 0.12) 0%, rgba(255, 255, 255, 0.97) 100%);
  transition: background 0.3s ease;
}

/* 图标旋转动画 */
.card .bi {
  transition: transform 0.3s ease;
}

.card:hover .bi {
  transform: rotate(360deg);
}
</style>
